package ru.hh.team02.chat.database;


import ru.hh.team02.chat.server.Services;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.LinkedList;
import java.util.List;

public class ConnectionPool {

    private final String url;

    private final int initCount = 10;

    private final List<Connection> connections = new LinkedList<Connection>();


    public ConnectionPool(String url) throws ClassNotFoundException, SQLException, IllegalAccessException, InstantiationException {
        this.url = url;

        for (int count = 0; count < initCount; count++) {
            Connection connection = DriverManager.getConnection(url);
            connections.add(connection);
        }

    }

    public synchronized Connection getConnection() throws SQLException {
        Connection newConnection;
        if (connections.isEmpty()) {
            newConnection = DriverManager.getConnection(url);
        } else {
            newConnection = connections.remove(0);
        }

        return newConnection;

    }

    public synchronized void putConnection(final Connection connection){
        connections.add(connection);
        closeConnection(connection);
    }

    private static void closeConnection(final Connection connection) {
        try {
            connection.close();
        } catch (SQLException e) {
            Services.ADMIN_LOGGER.write("failed to close connection");
        }
    }
}
